//
//  JLVerifyCodeViewController.m
//  JLStyleApp
//
//  Created by LvJianfeng on 15/8/20.
//  Copyright (c) 2015年 JLStyle. All rights reserved.
//

#import "JLVerifyCodeViewController.h"
#import "JLCreatePersonMegViewController.h"
#import "LRTimerLabel.h"
#import "JLUserinfoDelegate.h"

@interface JLVerifyCodeViewController() <UIScrollViewDelegate, UITextFieldDelegate, LRTimerLabelDelegate, JLUserinfoDelegate>
{
    UIButton *doneInKeyboardButton;
    BOOL keyboardIsVisible;
    
    UILabel *time_show;
}
@property (strong, nonatomic) UIScrollView *scrollview;

@property (weak, nonatomic) UITextField *verifyCodeTextView;
@property (weak, nonatomic) UIButton *getVerifyCodeButton;

@property (strong, nonatomic) UIButton *confirmButton;
@end

@implementation JLVerifyCodeViewController
-(void)viewDidLoad{
    [super viewDidLoad];
    keyboardIsVisible = YES;
    self.title = @"验证码";
    self.view.backgroundColor = [UIColor customControllerBackgroundColor];
    [self.view addSubview:self.scrollview];
    
    [self setupUI];
    
    [self timeCount];
    
    [self.scrollview addSubview:self.confirmButton];
}

-(void)finishAction{
    [self.verifyCodeTextView resignFirstResponder];
}

- (void)confirmAction{
    [self.verifyCodeTextView resignFirstResponder];
    if (self.verifyCodeTextView.text.length != 4) {
        [JFGlobalInstance showAlertLabel:self.navigationController.view text:@"(T^T)验证码位数不足" afterDelay:2.f];
    }else{
        [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        [SMS_SDK commitVerifyCode:self.verifyCodeTextView.text result:^(enum SMS_ResponseState state) {
            if (state == 1) {
                [JFGlobalInstance showAlertLabel:self.navigationController.view text:@"验证成功" afterDelay:1.f];
                [JLUserinfo do_register:self.phone password:self.password delegate:self];
            }else if (state == 0){
                [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
                [JFGlobalInstance showAlertLabel:self.navigationController.view text:@"(T^T)验证失败，重新获取验证码" afterDelay:2.f];
            }
        }];
    }
}

- (void)getVerifyCodeButtonAction{
    [self timeCount];
    //区域
    NSString* areaCode = [AreaCode stringByReplacingOccurrencesOfString:@"+" withString:@""];
    //发送验证码
    [SMS_SDK getVerificationCodeBySMSWithPhone:self.phone zone:areaCode result:^(SMS_SDKError *error) {
        if (!error) {
            [JFGlobalInstance showAlertLabel:self.navigationController.view text:@"验证码获取中..." afterDelay:2.f];
        }else{
            [JFGlobalInstance showAlertLabel:self.navigationController.view text:@"(%>_<%)验证码发送错误了,会不会太平凡了" afterDelay:2.f];
        }
    }];
}

//键盘
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setCustomBackgroundColor:GlobalColor];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification object:nil];
}

//退出时移除观察者
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.verifyCodeTextView resignFirstResponder];
}

#pragma mark JLUserinfoDelegate
- (void)operatingResult:(BOOL)isOK stateCode:(int)state{
    [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
    if (isOK) {
        [self performSelector:@selector(goAddMessage) withObject:nil afterDelay:0.f];
    }else{
        NSLog(@"注册本地数据库插入失败。");
    }
}

#pragma mark 验证成功进入以下一个界面
- (void)goAddMessage{
    //验证码输入对了跳转到个人信息界面
    JLCreatePersonMegViewController *cpmvc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:NSStringFromClass([JLCreatePersonMegViewController class])];
    [self.navigationController pushViewController:cpmvc animated:YES];
}

#pragma mark 键盘消息方法
- (void)keyboardWillShow:(NSNotification*)aNotification
{
    //判断doneInKeyboardButton==nil
    if (doneInKeyboardButton==nil) {
        [self configDoneInKeyBoardButton];
    }
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    keyboardIsVisible = YES;
    if (doneInKeyboardButton) {
        [doneInKeyboardButton removeFromSuperview];
        doneInKeyboardButton = nil;
        //让手机号输入框失去第一响应,确保每一响应都会去创建确认按钮
        [self.verifyCodeTextView resignFirstResponder];
    }
}

//拖动将结束
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    keyboardIsVisible = YES;
    [self.view endEditing:YES];
}

//配置界面
- (void)setupUI{
    UIView *textFieldBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, ScreenWidth, 50)];
    textFieldBackView.backgroundColor = [UIColor whiteColor];
    [self.scrollview addSubview:textFieldBackView];
    //文本框
    UITextField *verifyCodeTextView = [[UITextField alloc] init];
    verifyCodeTextView.delegate = self;
    verifyCodeTextView.placeholder = @"验证码";
    verifyCodeTextView.textColor = [UIColor customLightPlaceColor];
    verifyCodeTextView.font = JLFont(16);
    verifyCodeTextView.keyboardType = UIKeyboardTypeNumberPad;
    verifyCodeTextView.returnKeyType = UIReturnKeyDone;
    verifyCodeTextView.clearButtonMode = UITextFieldViewModeWhileEditing;
    verifyCodeTextView.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
    verifyCodeTextView.leftViewMode = UITextFieldViewModeAlways;
    verifyCodeTextView.frame = CGRectMake(0, 0, ScreenWidth-100, 50);
    [textFieldBackView addSubview:verifyCodeTextView];
    self.verifyCodeTextView = verifyCodeTextView;
    
    UIButton *getVerifyCodeButton = [[UIButton alloc] init];
    [getVerifyCodeButton setTitle:@"重新获取" forState:UIControlStateNormal];
    [getVerifyCodeButton setTitleColor:[UIColor customSystemColor] forState:UIControlStateNormal];
    getVerifyCodeButton.titleLabel.font = JLFont(18);
    getVerifyCodeButton.frame = CGRectMake(ScreenWidth-100, 0, 100, 50);
    [getVerifyCodeButton addTarget:self action:@selector(getVerifyCodeButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [textFieldBackView addSubview:getVerifyCodeButton];
    self.getVerifyCodeButton = getVerifyCodeButton;
}

#pragma mark - textField Delegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    //创建确认键
    [self configDoneInKeyBoardButton];
}
- (void)configDoneInKeyBoardButton{
    //初始化
    if (doneInKeyboardButton == nil)
    {
        doneInKeyboardButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [doneInKeyboardButton setTitle:@"确认" forState:UIControlStateNormal];
        [doneInKeyboardButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        doneInKeyboardButton.adjustsImageWhenHighlighted = NO;
        [doneInKeyboardButton addTarget:self action:@selector(finishAction) forControlEvents:UIControlEventTouchUpInside];
    }
    //每次必须从新设定“确认”按钮的初始化坐标位置
    doneInKeyboardButton.frame = CGRectMake(0, ScreenHeight+216, 122, 53);
    
    //由于ios8下，键盘所在的window视图还没有初始化完成，调用在下一次 runloop 下获得键盘所在的window视图
    [self performSelector:@selector(addDoneButton) withObject:nil afterDelay:0.0f];
}
#pragma mark -实现事件
- (void) addDoneButton{
    //获得键盘所在的window视图
    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
    [tempWindow addSubview:doneInKeyboardButton];// 注意这里直接加到window上
    
    if (keyboardIsVisible) {
        [UIView animateWithDuration:0.25 delay:0.0 options:7 << 16 animations:^{
            doneInKeyboardButton.transform = CGAffineTransformMakeTranslation(0, -269);
        } completion:^(BOOL finished) {
            keyboardIsVisible = NO;
        }];
    }else{
        doneInKeyboardButton.frame = CGRectMake(0, ScreenHeight-53, 106, 53);
    }
    
    
}


#pragma mark-textField的代理
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField{
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    //你的每一次输入的都会执行到这里
    return YES;
}

- (void) timeCount{
    [self.getVerifyCodeButton setTitle:nil forState:UIControlStateNormal];
    time_show = [[UILabel alloc] initWithFrame:self.getVerifyCodeButton.bounds];
    [self.getVerifyCodeButton addSubview:time_show];
    LRTimerLabel *time_cutDown = [[LRTimerLabel alloc] initWithLabel:time_show andTimerType:MZTimerLabelTypeTimer];
    [time_cutDown setCountDownTime:60];
    time_cutDown.timeFormat = @"s秒";
    time_cutDown.timeLabel.textColor = [UIColor customLightPlaceColor];
    time_cutDown.timeLabel.font = [UIFont systemFontOfSize:17.f];
    time_cutDown.timeLabel.textAlignment = NSTextAlignmentCenter;
    time_cutDown.delegate = self;
    self.getVerifyCodeButton.userInteractionEnabled = NO;
    
    [time_cutDown start];
}

#pragma mark - LRTimerLabelDelegate

- (void)timerLabel:(LRTimerLabel *)timerLabel finshedCountDownTimerWithTime:(NSTimeInterval)countTime{
    [self.getVerifyCodeButton setTitle:@"重新获取" forState:UIControlStateNormal];
    [time_show removeFromSuperview];
    self.getVerifyCodeButton.userInteractionEnabled = YES;
}

#pragma mark lazyload

- (UIButton *)confirmButton{
    if (_confirmButton==nil) {
        CGFloat registerButtonW = ScreenWidth-40;
        _confirmButton = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth/2-registerButtonW/2, self.verifyCodeTextView.center.y+25+50, registerButtonW, 50)];
        _confirmButton.titleLabel.textColor = [UIColor whiteColor];
        _confirmButton.backgroundColor = GlobalColor;
        _confirmButton.titleLabel.font = JLBlodFont(18);
        _confirmButton.layer.cornerRadius = 25;
        [_confirmButton setTitle:@"确认" forState:UIControlStateNormal];
        
        [_confirmButton addTarget:self action:@selector(confirmAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmButton;
}

-(UIScrollView *)scrollview{
    if (_scrollview==nil) {
        _scrollview = [[UIScrollView alloc] initWithFrame:self.view.bounds];
        _scrollview.showsVerticalScrollIndicator = NO;
        _scrollview.showsHorizontalScrollIndicator = NO;
        _scrollview.delegate = self;
    }
    return _scrollview;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
